package xjutils

import (
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"strconv"
)

func SelectOneHealthyInstance(client naming_client.INamingClient, IpAddr string, Port uint64, ServiceName string) (instance string, err error) {
	if client == nil {
		sc := []constant.ServerConfig{
			{
				IpAddr: IpAddr,
				Port:   Port,
			},
		}

		cc := constant.ClientConfig{
			TimeoutMs: 5000,
			LogDir:    `log`,
			CacheDir:  `cache`,
			LogLevel:  "error",
		}

		client, err = clients.CreateNamingClient(map[string]interface{}{
			"serverConfigs": sc,
			"clientConfig":  cc,
		})
		if err != nil {
			return "", err
		}
	}

	//SelectOneHealthyInstance return one instance by WRR strategy for load balance
	//And the instance should be health=true,enable=true and weight>0
	//ClusterName=DEFAULT,GroupName=DEFAULT_GROUP
	instances, err := client.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
		ServiceName: ServiceName,
	})
	if err != nil {
		return "", err
	}
	return "http://" + instances.Ip + ":" + strconv.Itoa(int(instances.Port)), nil
}
